package com.bum.api.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

@SuppressWarnings("serial")
public class FetchServlet extends HttpServlet {
	public static final String[] BROWSER_HEADERS = {
			"User-Agent",
			"Mozilla/5.0 (Linux; U; Android 2.2; en-us; DROID2 GLOBAL Build/S273) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
			"Accept", "text/plain, text/html", "Accept-Charset",
			"UTF-8,*;q=0.5", "Accept-Language",
			"en-US,en;q=0.8,vi;q=0.6,fr-FR;q=0.4,fr;q=0.2", "Cache-Control",
			"max-age=0", "Connection", "close" };

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");

		String url = req.getParameter("url");
		if (StringUtils.isNotBlank(url) && url.startsWith("http")) {
			try {
				url = URLDecoder.decode(url, "utf-8");
				System.out.println(url);

				URL u = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) u.openConnection();

				for (int i = 0, n = BROWSER_HEADERS.length / 2; i < n; i++) {
					conn.setRequestProperty(BROWSER_HEADERS[2 * i],
							BROWSER_HEADERS[2 * i + 1]);
				}
				conn.setRequestProperty("Host", u.getHost());

				String headers = req.getParameter("headers");
				if (StringUtils.isNotBlank(headers)) {
					String[] arrayHeader = StringUtils.split(headers, "|");
					if (arrayHeader.length > 0) {
						for (int i = 0, n = arrayHeader.length / 2; i < n; i++) {
							conn.setRequestProperty(arrayHeader[2 * i],
									arrayHeader[2 * i + 1]);
						}
					}
				}

				System.out.println(conn.getRequestProperties().toString());
				if (conn.getResponseCode() != 200) {
					return;
				}

				InputStream is = conn.getInputStream();

				String callback = req.getParameter("callback");
				if (StringUtils.isNotEmpty(callback)) {
					resp.setContentType("application/json");
					String text = IOUtils.toString(is, "UTF-8");
					if (text != null) {
						text = text.replaceAll("[\n\r]", "")
								.replaceAll("[\\s]+", " ")
								.replace("\"", "\\\"");
						text = callback + "(\"" + text + "\")";
						IOUtils.write(text.getBytes("UTF-8"),
								resp.getOutputStream());
					}
				} else {
					// for (Map.Entry<String, List<String>> entry :
					// conn.getHeaderFields().entrySet()) {
					// resp.setHeader(entry.getKey(), entry.getValue().get(0));
					// }
					resp.setContentType(conn.getContentType());
					resp.setContentLength(conn.getContentLength());
					resp.setHeader("Cache-Control", "max-age=31536000");
					resp.setHeader("Date", "max-age=31536000");
					resp.setHeader("Expires", "Sun, 13 Sep 2035 03:34:58 GMT");
					resp.setHeader("Last-Modified", "Wed, 15 Nov 1995 04:58:08 GMT");
					resp.setHeader("Etag", "E" + url.hashCode());

					IOUtils.copy(is, resp.getOutputStream());
				}
			} catch (Throwable e) {
				e.printStackTrace();
				resp.getWriter().write(e.getMessage());
			}
		}
	}

	@Override
	protected long getLastModified(HttpServletRequest req) {
		return 0;
	}
}
